/**
 * 初始化数据
 */
const dataList = genMockData(10);
const A = 1000;
let B = A,
  C = 0;
/**
 * 生成数据
 */
function genMockData(num) {
  let r = [];
  for (let i = 0; i < num; i++) {
    r.push({ id: i, count: (i + 1) * 20 });
  }
  return r;
}

let VM = (function () {
  const method = {
    list() {

    },
  };
  /**
   * 生成模板
   */
  function genListTemplate(data) {
    let wrapper = document.createDocumentFragment(),
      ul = document.createElement("ul");
    ul.className = "list";
    ul.addEventListener("click", function (event) {
      let checkedItems = getAllCheckedItems(data);
      calculate(checkedItems);
    });
    wrapper.appendChild(ul);
    data.forEach((item, i) => {
      let listItem = genListItem(item, i);
      ul.appendChild(listItem);
    });
    return wrapper;
  }
  function genListItem(item, id) {
    let li = document.createElement("li");
    li.id = `item-${id}`;
    let input = document.createElement("input"),
      span = document.createElement("span"),
      b = document.createElement("span");
    input.className = "checkbox";
    input.type = "checkbox";
    span.className = "count";
    b.className = "count";
    span.innerHTML = `      count: ${item.count}`;
    b.innerHTML = `      b: Not Calculated`;
    b.id = `b-${id}`;
    li.appendChild(input);
    li.appendChild(span);
    li.appendChild(b);
    return li;
  }
  /**
   * 获取所有已选项
   * @param {*} data
   * @returns
   */
  function getAllCheckedItems(data) {
    let inputs = document.getElementsByTagName("input"),
      r = [];
    [].slice.call(inputs).forEach((input) => {
      if (input.checked) {
        let i = parseInt(input.parentNode.id.replace("item-", ""));
        r.push(data[i]);
      }
    });
    return r;
  }
  /**
   * 更新并绑定数据到模板
   */
  function bindDataToTemplate(init) {
    init = init || true;
    if (init) document.getElementById("A").innerHTML = A;
    document.getElementById("B").innerHTML = B;
    document.getElementById("C").innerHTML = C;
  }

  /**
   * 逻辑计算
   */
  function calculate(items) {
    if (items.length === 0) {
      B = A;
      C = 0;
    }
    let sumb = 0,
      i = 0;
    B = A;
    while (i < items.length) {
      let b = items[i].count <= B ? items[i].count : B;
      sumb += b;
      C = sumb;
      B = A - sumb;
      document.getElementById(`b-${items[i].id}`).innerHTML = `      b: ${b}`;
      i++;
    }
    bindDataToTemplate(false);
  }
  return function () {
    let container = document.getElementById("root");
    container.appendChild(genListTemplate(dataList));
    bindDataToTemplate();
  };
})(window);

window.onload = function () {
  VM();
};
